package com.moxi.mogublog.swagger.config;

import com.moxi.mogublog.swagger.properties.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * Swagger2的接口配置
 * <p/>
 * Profile -- Spring 提供的可以根据当前环境，动态的激活和切换一系列组件的功能。指定组件在哪个环境的情况下才能被注册到容器中，不指定，任何环境下都能注册这个组件
 *
 * @author JackLi
 * @version 1.0
 * @date 2020-04-21
 */
@Profile(value = {"dev", "test"})
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * Swagger配置
     */
    @Autowired
    private SwaggerProperties sp;

    /**
     * 创建API
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {

        // swagger ui 添加header请求头参数: https://blog.csdn.net/zhuchunyan_aijia/article/details/90610869
        //=====添加head参数start============================
        List<Parameter> paras = new ArrayList<Parameter>();
        ParameterBuilder tokenParam = new ParameterBuilder();
        tokenParam.name("token")
                .description("Token令牌")
                .modelRef(new ModelRef("String"))
                .parameterType("header")
                .required(false)
                .build();
        paras.add(tokenParam.build());
        // =========添加head参数end===================

        return new Docket(DocumentationType.SWAGGER_2).
                useDefaultResponseMessages(false)
                // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api，用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描指定包中的swagger注解
                //.apis(RequestHandlerSelectors.basePackage(sp.getBasePackage()))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("^(?!auth).*$"))
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .globalOperationParameters(paras)
                ;
    }

    /**
     * 安全模式，这里指定token通过Authorization头请求头传递
     *
     * @return
     */
    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = newArrayList();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     *
     * @return
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContextList = newArrayList();
        securityContextList.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContextList;
    }

    /**
     * 默认的安全上引用
     *
     * @return
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferenceList = newArrayList();
        securityReferenceList.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferenceList;
    }

    /**
     * 添加摘要信息
     *
     * @return
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title(sp.getTitle())
                // 描述
                .description(sp.getDescription())
                // 服务条款网址
                .license(sp.getLicense())
                .licenseUrl(sp.getLicenseUrl())
                .termsOfServiceUrl(sp.getTermsOfServiceUrl())
                // 作者信息
                .contact(new Contact(sp.getContact().getName(), sp.getContact().getUrl(), sp.getContact().getEmail()))
                // 版本
                .version(sp.getVersion())
                .build();
    }

}
